const { result ,isNumber,parseArrayString} = require("common-utils");
const uniID=require("uni-id-common");
const db = uniCloud.database();
const dbCmd = db.command;
const uniCloudObject = uniCloud.importObject("uni-id-co", {customUI: true});
module.exports = {
	_before:async function () { // 通用预处理器
		this.httpInfo = this.getHttpInfo();	
		let {httpMethod="GET",headers:{token},queryStringParameters=null,body=null} = this.httpInfo
		this.httpMethod = httpMethod.toUpperCase();
		this.queryStringParameters = queryStringParameters;
		this.body = body ? JSON.parse(body) : null;
		if(!token) throw result({code:401,msg:"required",custom:"必须传递token"});
		const clientInfo = this.getClientInfo()
		const uniIDIns = uniID.createInstance({
			clientInfo
		})
		this.token = token;
		this.userInfo =  await uniIDIns.checkToken(token);		
		if(this.userInfo.errCode == 'uni-id-check-token-failed') throw result({code:403,msg:"error",custom:"token校验未通过"});
		if(this.userInfo.errCode == 'uni-id-token-expired') throw result({code:401,msg:"error",custom:"token已失效"});	
	},
	//获取登录用户的信息
	async getUserInfo(){		
		try{
			if(this.httpMethod!="GET") return result({code:400,msg:"error",custom:"method类型需要GET"});
			let {data} = await db.collection("uni-id-users").doc(this.userInfo.uid).field({
				_id:true,
				username:true,
				nickname:true,
				role:true,
				register_date:true,
				last_login_date:true,
				avatar:true,
				dcloud_appid:true
			}).get();			
			return result({code:200,msg:"success",data:data[0]});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});	
		}		
	},
	
	//获取用户列表
	async userlist({pageNum=1,pageSize=8,keyword}={}){
		try{
			if(this.httpMethod!="GET") return result({code:400,msg:"error",custom:"method类型需要GET"});
			pageSize = pageSize>50 ? 50 : Number(pageSize);
			let skipNum = (pageNum-1) * pageSize;		
			let screen = {is_delete:dbCmd.neq(true)};
			if(keyword) screen.username = new db.RegExp({
				regex: keyword,
				options: 'i',
			});
			
			let res1 = db.collection("uni-id-users")
			.where(screen)	
			.field({
				"_id":true,
				"username":true,
				"nickname":true,
				"role":true,
				"register_date":true,
				"last_login_date":true,
				"avatar":true,
				"dcloud_appid":true
			})
			.orderBy("_id","desc")
			.skip(skipNum)
			.limit(pageSize)			
			.get();	
			let res2 = db.collection("uni-id-users").where(screen).count();	
			let res = await Promise.all([res1,res2]);
			return result({code:200,msg:"success",data:res[0].data,total:res[1].total});	
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
	
	//新增用户
	async addUser({username,password,sort,target="self",appid}={}){
		try{
			if(this.httpMethod!="POST") return result({code:400,msg:"error",custom:"method类型需要POST"});
			let {username,nickname,password,authorizedApp=[],role=[],status=0} = this.body;
			if(!username) return result({code:400,msg:"required",custom:"必须传递username"});
			if(!password) return result({code:400,msg:"required",custom:"必须传递password"});
			if(!nickname) nickname = '匿名'+(Math.random().toString(36).substring(3,9));;			
			let isUser = await db.collection("uni-id-users").where({username}).count();
			if(isUser.total) return result({code:400,msg:"error",custom:username+",该用户已经被注册"});
			
			const {data} = await uniCloud.request({
				url:"https://fc-mp-54078533-0cb4-46b0-aa85-4d88df83247f.next.bspapp.com/uni-id-co/addUser",
				method: 'POST',
				dataType: 'json',
				headers: {
					'Content-Type': 'application/json'
				},
				data:{
					clientInfo:{
						uniPlatform:"web",
						appId:"__UNI__90184A1",
						deviceId:"17127172375149877743"
					},
					uniIdToken:this.token,
					params: {
						username,
						password,
						nickname,
						authorizedApp,
						role,
						status
					}
				}
			})
			if(data.errCode!=0) return result({code:400,msg:"error",custom:data.errMsg});
			return result({code:200,msg:"success"});			
			
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}	
	},
	
	//修改用户
	async updateUser(){
		try{
			if(this.httpMethod!="POST") return result({code:400,msg:"error",custom:"method类型需要POST"});
			let {username,nickname,password,authorizedApp=[],role=[],status=0,uid} = this.body;
			if(!username) return result({code:400,msg:"required",custom:"必须传递username"});
			if(!password) return result({code:400,msg:"required",custom:"必须传递password"});
			if(!uid) return result({code:400,msg:"required",custom:"必须传递uid"});
			if(!nickname) nickname = '匿名'+(Math.random().toString(36).substring(3,9));;			
			
			
			const {data} = await uniCloud.request({
				url:"https://fc-mp-54078533-0cb4-46b0-aa85-4d88df83247f.next.bspapp.com/uni-id-co/updateUser",
				method: 'POST',
				dataType: 'json',
				headers: {
					'Content-Type': 'application/json'
				},
				data:{
					clientInfo:{
						uniPlatform:"web",
						appId:"__UNI__90184A1",
						deviceId:"17127172375149877743"
					},
					uniIdToken:this.token,
					params: {
						uid,
						username,
						password,
						nickname,
						authorizedApp,
						role,
						status
					}
				}
			})
			if(data.errCode!=0) return result({code:400,msg:"error",custom:data.errMsg});
			return result({code:200,msg:"success"});			
			
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}	
	},
	
	//删除用户
	async removeUser(){
		try{
			if(this.httpMethod!="DELETE") return result({code:400,msg:"error",custom:"method类型需要DELETE"});
			let {ids} = this.body;
			if(!ids) return result({code:400,msg:"required",custom:"必须传递ids"});
			let res = await db.collection("uni-id-users").where({
				_id:dbCmd.in(ids)
			}).remove()			
			if(res.deleted) return result({code:200,msg:"success",custom:`删除${res.deleted}条`});
			return result({code:400,msg:"error",custom:`删除${res.deleted}条`});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
	
	
	
	
	//可登录应用
	async applist(){
		try{
			let res = await db.collection("opendb-app-list").get();
			return result({code:200,msg:"success",data:res.data});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
	
	//角色列表
	async rolelist(){
		try{
			let res = await db.collection("uni-id-roles").get();
			return result({code:200,msg:"success",data:res.data});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});	
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
}
